﻿#region Usings

using System;
using System.Collections;
using System.Globalization;
using System.Web.UI.WebControls;

using DotNetNuke.Common.Lists;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Framework;
using DotNetNuke.Security.Roles;
using DotNetNuke.Security.Roles.Internal;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.Utilities;
using DotNetNuke.Web.UI.WebControls.Extensions;

using Globals = DotNetNuke.Common.Globals;

using BuRU = VLUNewsBusiness.VLURolesAndUsers;
using BuUtil = VLUNewsBusiness.Utilities;
using DotNetNuke.Security;

#endregion

namespace VLUNewsUI.VLURolesAndUsers
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditRoles PortalModuleBase is used to manage a Security Role
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
    ///                       and localisation
    /// </history>
    /// -----------------------------------------------------------------------------
    public partial class EditRoles : PortalModuleBase
    {
        #region Private Members

        private int _roleID = -1;
        private int _roleGroupID = -1;

        #endregion

        #region Private Methods

        #endregion

        #region Event Handlers

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            jQuery.RequestDnnPluginsRegistration();

            cmdDelete.Click += OnDeleteClick;
            cmdManage.Click += OnManageClick;
            cmdUpdate.Click += OnUpdateClick;

            try
            {
                if (Request.QueryString["RoleGroupID"] != null)
                {
                    _roleGroupID = Int32.Parse(Request.QueryString["RoleGroupID"]);
                }
                else
                {
                    _roleGroupID = BuRU.RoleAndUser.GetNewsRoleGroupID();
                }

                if ((Request.QueryString["RoleID"] != null))
                {
                    _roleID = Int32.Parse(Request.QueryString["RoleID"]);
                }
                //var objPortalController = new PortalController();
                //var objPortalInfo = objPortalController.GetPortal(PortalSettings.PortalId);
                if (Page.IsPostBack == false)
                {
                    string confirmString = Localization.GetString("ConfirmUnRegister", LocalResourceFile);
                    ClientAPI.AddButtonConfirm(cmdDelete, confirmString);

                    cmdCancel.NavigateUrl = Globals.NavigateURL();
                    //var role = TestableRoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == _roleID);
                    //txtRoleName.Text = role.RoleName;

                    ctlIcon.FileFilter = Globals.glbImageFileTypes;
                    if (_roleID != -1)
                    {
                        lblRoleName.Visible = true;
                        txtRoleName.Visible = false;
                        valRoleName.Enabled = false;

                        var role = TestableRoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == _roleID);
                        if (role != null)
                        {
                            lblRoleName.Text = role.RoleName;
                            txtDescription.Text = role.Description;
                            ctlIcon.Url = role.IconFile;
                            cmdManage.Visible = role.Status == RoleStatus.Approved;
                        }
                        else //security violation attempt to access item not related to this Module
                        {
                            Response.Redirect(Globals.NavigateURL("Security Roles"));
                        }

                        if (_roleID == PortalSettings.AdministratorRoleId || _roleID == PortalSettings.RegisteredRoleId)
                        {
                            cmdDelete.Visible = false;
                        }
                        if (_roleID == PortalSettings.RegisteredRoleId)
                        {
                            cmdManage.Visible = false;
                        }
                    }
                    else
                    {
                        cmdDelete.Visible = false;
                        cmdManage.Visible = false;
                        lblRoleName.Visible = false;
                        txtRoleName.Visible = true;
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdUpdate_Click runs when the update Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// 	[jlucarino]	2/23/2009	Added CreatedByUserID and LastModifiedByUserID
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnUpdateClick(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    float sglServiceFee = 0;
                    var intBillingPeriod = 1;
                    var strBillingFrequency = "N";

                    //if (cboBillingFrequency.SelectedItem.Value == "N" && !String.IsNullOrEmpty(txtServiceFee.Text))
                    //{
                    //    DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("IncompatibleFee", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                    //    return;
                    //}
                    //if (!String.IsNullOrEmpty(txtServiceFee.Text) && !String.IsNullOrEmpty(txtBillingPeriod.Text) && cboBillingFrequency.SelectedItem.Value != "N")
                    //{
                    //    sglServiceFee = float.Parse(txtServiceFee.Text);
                    //    intBillingPeriod = int.Parse(txtBillingPeriod.Text);
                    //    strBillingFrequency = cboBillingFrequency.SelectedItem.Value;
                    //}
                    float sglTrialFee = 0;
                    var intTrialPeriod = 1;
                    var strTrialFrequency = "N";

                    //if (sglServiceFee != 0 && !String.IsNullOrEmpty(txtTrialFee.Text) && !String.IsNullOrEmpty(txtTrialPeriod.Text) && cboTrialFrequency.SelectedItem.Value != "N")
                    //{
                    //    sglTrialFee = float.Parse(txtTrialFee.Text);
                    //    intTrialPeriod = int.Parse(txtTrialPeriod.Text);
                    //    strTrialFrequency = cboTrialFrequency.SelectedItem.Value;
                    //}

                    var role = new RoleInfo
                                   {
                                       PortalID = PortalId,
                                       RoleID = _roleID,
                                       RoleGroupID = _roleGroupID,
                                       RoleName = txtRoleName.Text,
                                       Description = txtDescription.Text,
                                       ServiceFee = sglServiceFee,
                                       BillingPeriod = intBillingPeriod,
                                       BillingFrequency = strBillingFrequency,
                                       TrialFee = sglTrialFee,
                                       TrialPeriod = intTrialPeriod,
                                       TrialFrequency = strTrialFrequency,
                                       IsPublic = false,
                                       AutoAssignment = false,
                                       SecurityMode = SecurityMode.SecurityRole,
                                       Status = RoleStatus.Approved,
                                       RSVPCode = String.Empty,
                                       IconFile = ctlIcon.Url
                                   };
                    if (_roleID == -1)
                    {
                        if (TestableRoleController.Instance.GetRole(PortalId, r => r.RoleName == role.RoleName) == null)
                        {
                            TestableRoleController.Instance.AddRole(role);
                        }
                        else
                        {
                            DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("DuplicateRole", LocalResourceFile), ModuleMessage.ModuleMessageType.RedError);
                            return;
                        }
                    }
                    else
                    {
                        //TestableRoleController.Instance.UpdateRole(role);
                        RoleController oRoleController = new RoleController();
                        oRoleController.UpdateRole(role);
                    }
					
                    //Clear Roles Cache
                    DataCache.RemoveCache("GetRoles");

                    Response.Redirect(Globals.NavigateURL());
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnDeleteClick(object sender, EventArgs e)
        {
            if (PortalSecurity.IsInRole(BuUtil.BaseSettings.NewsAdminRoleName) == true)
            {
                return;
            }
            try
            {
                var role = TestableRoleController.Instance.GetRole(PortalSettings.PortalId, r => r.RoleID == _roleID);

                TestableRoleController.Instance.DeleteRole(role);
              
                //Clear Roles Cache
                DataCache.RemoveCache("GetRoles");

                Response.Redirect(Globals.NavigateURL());
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdManage_Click runs when the Manage Users Button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// 	[cnurse]	9/10/2004	Updated to reflect design changes for Help, 508 support
        ///                       and localisation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void OnManageClick(Object sender, EventArgs e)
        {
            try
            {
                //Response.Redirect(EditUrl("RoleId", _roleID.ToString(), "User Roles"));
                Response.Redirect(Globals.NavigateURL("User Roles", "RoleId=" + _roleID.ToString()));
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion
    }
}